package com.offcn.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "Authorization"; //令牌的标识

    private static final String USER_LOGIN_URL = "http://localhost:10001/oauth/login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("全局拦截器已执行");

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求的URI  localhost:10086/xxxxx
        String path = request.getURI().getPath();
        String uri = request.getURI().toString();

        if (path.startsWith("/api/user/login") || path.startsWith("/api/brand/search")) {
            // 放行请求
            Mono<Void> filter = chain.filter(exchange);

            return filter;
        }
        if (URLFilter.hasAuth(uri)) {
            return chain.filter(exchange);
        }
        // 从头文件 根据 令牌标识 进行 获取 令牌

        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        if (StringUtils.isEmpty(token)) {
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        }

        // 从cookie中  根据 令牌标识 进行 获取 令牌
        HttpCookie first = request.getCookies().getFirst(AUTHORIZE_TOKEN);
        if (first != null) {
            token = first.getValue();
        }
        // 如果两次都没取到token ，输出错误代码
        if (StringUtils.isEmpty(token)) {
//            response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
//            return response.setComplete();
            return needAuth(USER_LOGIN_URL, exchange, uri);
        }
        System.out.println("token:" + token);


        // 如果有令牌，解析令牌数据
        try {
            //request.mutate().header(AUTHORIZE_TOKEN, token);
            ServerHttpRequest.Builder mutate = request.mutate();
            mutate.header(AUTHORIZE_TOKEN,"Bearer "+token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    private Mono<Void> needAuth(String userLoginUrl, ServerWebExchange exchange, String uri) {

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",userLoginUrl+"?from="+uri);

        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
